package com.whw.fy.service.impl;

import cn.hutool.json.JSONUtil;
import com.whw.fy.config.GlobalConfig;
import com.whw.fy.entity.Message;
import com.whw.fy.entity.Parent;
import com.whw.fy.entity.Staff;
import com.whw.fy.entity.Student;
import com.whw.fy.exception.ServerCommunicateException;
import com.whw.fy.mapper.ParentMapper;
import com.whw.fy.mapper.StaffMapper;
import com.whw.fy.mapper.StudentMapper;
import com.whw.fy.service.UserService;
import com.whw.fy.utils.JwtUtil;
import com.whw.fy.utils.WeChatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@Service
public class UserImpl implements UserService {

    @Resource
    private StaffMapper staffMapper;
    @Resource
    private ParentMapper parentMapper;
    @Resource
    private GlobalConfig globalConfig;
    @Resource
    private StudentMapper studentMapper;

    private Logger logger= LoggerFactory.getLogger(getClass());

    @Override
    public Message adminLogin(int userId, String pwd) {
        Staff staff = staffMapper.selectByStaffIdAndStaffPwd(userId,pwd);
        if (staff!=null){
            return Message.success("登陆成功").add(JwtUtil.createJwtToken(staff));
        }else{
            return Message.fail("账号密码错误！");
        }
    }

    @Override
    public Message miniProgramTeacherLogin(String jsCode) {
        String rs = WeChatUtil.wechatLogin(jsCode,globalConfig.programAppId,globalConfig.programAppSecret);
        logger.info("微信登录：jsCode：{}，result：{}",jsCode,rs);
        String openId= JSONUtil.parseObj(rs).getStr("openid");
        if (openId==null)
            throw new ServerCommunicateException();

        Staff staff = staffMapper.selectByStaffOpenid(openId);
        if (staff!=null){
            return Message.success(null).add(staff);
        }
        else {
            return Message.fail("请先绑定员工工号").add(openId);
        }

    }

    @Override
    public Message bindingOpenIdByStaffId(String openId, int staffId) {
       Staff staff = staffMapper.selectByPrimaryKey(staffId);
       if (staff!=null){
           return staffMapper.updateStaffOpenidByStaffId(openId,staffId)>0?Message.success("绑定成功！"):Message.fail(null);
       }else {
           return Message.fail("该员工不存在！");
       }
    }

    @Override
    public Message cancelBindingOpenIdByStaffId(int staffId) {
        return staffMapper.updateStaffOpenidByStaffId(null,staffId)>0?Message.success("解绑成功！"):Message.fail(null);
    }

    @Override
    public Message updateParentStatus(int parentId, int status) {
        return parentMapper.updateParentStatusByParentId(status,parentId)>0?Message.success(null):Message.fail(null);
    }

    @Override
    public Message bindOpenIdByParentCall(String openId, String parentCall) {
        Parent parent = parentMapper.selectAllByParentCall(parentCall);
        if (parent!=null){
            return parentMapper.updateParentOpenidByParentCall(openId,parentCall)>0?Message.success("绑定成功！"):Message.fail(null);
        }else {
            return Message.fail("该家长不存在！");
        }
    }

    @Override
    public Message miniProgramParentLogin(String jsCode) {
        String rs = WeChatUtil.wechatLogin(jsCode,globalConfig.programAppId,globalConfig.programAppSecret);
        logger.info("微信登录：jsCode：{}，result：{}",jsCode,rs);
        String openId= JSONUtil.parseObj(rs).getStr("openid");
        if (openId==null)
            throw new ServerCommunicateException();
        Parent parent = parentMapper.selectByParentOpenid(openId);
        if (parent!=null){
            return Message.success(null).add(parent);
        }
        else {
            return Message.fail("请先绑定家长").add(openId);
        }
    }

    @Override
    public Message miniProgramLogin(String jsCode) {
        String rs = WeChatUtil.wechatLogin(jsCode,globalConfig.programAppId,globalConfig.programAppSecret);
        logger.info("微信登录：jsCode：{}，result：{}",jsCode,rs);
        String openId= JSONUtil.parseObj(rs).getStr("openid");
        if (openId==null)
            throw new ServerCommunicateException();
        Parent parent = parentMapper.selectByParentOpenid(openId);

        if (parent!=null){
            HashMap hashMap = new HashMap();
            if (parent.getChildId()!=null&&parent.getChildId()!=""){
                String[] studentIds = parent.getChildId().split(";");
                List<Student> studentList = new LinkedList<>();
                if (studentIds.length>0){
                    for (String studentId:studentIds){
                        Student student = studentMapper.selectByPrimaryKey(Integer.parseInt(studentId));
                        studentList.add(student);
                    }
                    hashMap.put("studentList",studentList);
                }
                else {
                    hashMap.put("studentList",null);
                }

            }else {
                hashMap.put("studentList",null);
            }
            hashMap.put("parent",parent);
            hashMap.put("type",2);
            return Message.success(null).add(hashMap);
        }
        else {
            Staff staff = staffMapper.selectByStaffOpenid(openId);
            if (staff!=null){
                HashMap hashMap = new HashMap();
                hashMap.put("staff",staff);
                hashMap.put("type",1);
                return Message.success(null).add(hashMap);
            }
            else {
                return Message.fail("请先绑定身份").add(openId);
            }

        }

    }
    @Override
    public Message cancelBindOpenIdByParentCall(String parentCall) {
        return parentMapper.updateParentOpenidByParentCall(null,parentCall)>0?Message.success("解绑成功！"):Message.fail(null);
    }


}
